package com.top.art.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.top.art.annotation.PermissionLimit;
import com.top.art.bo.LoginInfoBO;
import com.top.art.converter.UserInfoConverter;
import com.top.art.entity.UserInfo;
import com.top.art.exception.ArtException;
import com.top.art.service.IUserInfoService;
import com.top.art.tool.AuthTool;
import com.top.art.tool.JwtToken;
import com.top.art.vo.AccountInfoVO;
import com.top.art.vo.ResVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * The type User controller.
 *
 * @author hjh
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

    /**
     * jwtToken
     */
    @Resource
    private JwtToken jwtToken;

    /**
     * user info
     */
    @Autowired
    private IUserInfoService userInfoService;

    /**
     * converter
     */
    @Resource
    private UserInfoConverter userInfoConverter;

    @Autowired
    private HttpServletResponse response;

    /**
     * Info protocol.
     *
     * @return the protocol
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ResVO<AccountInfoVO> info() {
        AccountInfoVO account = AuthTool.currentUser();
        return new ResVO<>(account);
    }

    /**
     * Login protocol.
     *
     * @param bo the bo
     * @return the protocol
     */
    @PermissionLimit(limit = false)
    @PostMapping(value = "/login")
    public ResVO<String> login(@Validated @RequestBody LoginInfoBO bo) {
        UserInfo userInfo = userInfoService.getOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getAccount, bo.getUsername())
                .eq(UserInfo::getEnable, 1));
        if (userInfo == null) {
            throw new ArtException(580, "用户不存在");
        }
        if (!StringUtils.equals(bo.getPassword(), userInfo.getPassword())) {
            throw new ArtException(581, "用户密码错误");
        }
        String token = jwtToken.generateToken(userInfoConverter.do2vo(userInfo));
        return new ResVO<>(token);
    }

    /**
     * Logout protocol.
     *
     * @return the protocol
     */
    @GetMapping(value = "/logout")
    public ResVO logout() {
        return new ResVO();
    }

}
